using System;
using System.Collections;
using Game.Framework;
using Game.Framework.FState;
using Scripts.Install;
using UnityEngine;

namespace Game.Install
{
    public class AppInstall : MonoBehaviour
    {
        private static AppInstall _instance;
        public static AppInstall Instance => _instance;
    
        private StateMachine<StateInstallBase> _stateMachine;
        
        [RuntimeInitializeOnLoadMethod]
        public static void AutoStart()
        {
            var main = new GameObject("AppInstall");
            main.AddComponent<AppInstall>();
            
        }

        private void Awake()
        {
            _instance = this;
            
            Application.targetFrameRate = 60;
            //关闭垂直同步
            QualitySettings.vSyncCount = 0;
            
            InitDebug();
            
            // StartCoroutine(Initialized());
            
            _stateMachine = new StateMachine<StateInstallBase>();
            _stateMachine.SetState<StateInstall>(null);
            
            EventBus.Register<EventNoAssetNeedDownLoad>(OnEventNoAssetNeedDownLoad);
        }

        private void OnDestroy()
        {
            EventBus.UnRegister<EventNoAssetNeedDownLoad>(OnEventNoAssetNeedDownLoad);
        }

        public void OnEventNoAssetNeedDownLoad(EventNoAssetNeedDownLoad e)
        {
            UIInstall.Close();
            LaunchApp();
        }

        // private IEnumerator Initialized()
        // {
        //     yield return YooAssetManager.Instance.Initialized();
        // }
    
        public void LaunchApp()
        {
            DllLoader.LoadHotUpdateDlls();

            var hotUpdateAss = DllLoader.LoadDll("Game.Runtime");
            var type = hotUpdateAss.GetType("Game.Applcation.App");
            type.GetMethod("Init")!.Invoke(null, null);

            DllLoader.UnloadDllTextRes();
            Destroy(gameObject);
        }

        private void InitDebug()
        {
#if DEVELOPMENT_BUILD || UNITY_EDITOR
            SRDebug.Init();
            Debug.unityLogger.logEnabled = true;
#endif
        }
    }
}


